package com.online.service_edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.online.service_edu.entity.EduSubject;
import com.online.service_edu.entity.SubjectData;
import com.online.service_edu.entity.treeSubject.OneLevelSubject;
import com.online.service_edu.entity.treeSubject.TwoLevelSubject;
import com.online.service_edu.listener.ExcelListener;
import com.online.service_edu.mapper.EduSubjectMapper;
import com.online.service_edu.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author hdc2008
 * @since 2021-02-09
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) throws IOException {

        EasyExcel.read(file.getInputStream(), SubjectData.class,new ExcelListener(eduSubjectService)).sheet().doRead();
    }

    @Override
    public List<OneLevelSubject> getSubTreeData() {
        //查询一级菜单的所有的
        QueryWrapper<EduSubject> wrapper= new QueryWrapper<>();
        wrapper.eq("parent_id",0);
        List<EduSubject> oneSubjects = baseMapper.selectList(wrapper);

        //查询二级菜单的所有的
        QueryWrapper<EduSubject> twoWrapper= new QueryWrapper<>();
        twoWrapper.ne("parent_id",0);
        List<EduSubject> twoSubjects = baseMapper.selectList(twoWrapper);

        List<OneLevelSubject> oneLevelSubjectList=new ArrayList<>();
//        开始循环所有的一级菜单
        for (EduSubject oneSubject : oneSubjects) {
            OneLevelSubject oneLevelSubject=new OneLevelSubject();

            BeanUtils.copyProperties(oneSubject,oneLevelSubject);

            List<TwoLevelSubject> twoLevelSubjectList=new ArrayList<>();
//            开始循环所有的二级菜单，如果是一级菜单的子菜单加入到children中去
            for (EduSubject twoSubject : twoSubjects) {
                if(twoSubject.getParentId().equals(oneSubject.getId())){
                    TwoLevelSubject twoLevelSubject=new TwoLevelSubject();
                    BeanUtils.copyProperties(twoSubject,twoLevelSubject);
                    twoLevelSubjectList.add(twoLevelSubject);
                }
            }
            oneLevelSubject.setChildren(twoLevelSubjectList);
            oneLevelSubjectList.add(oneLevelSubject);

        }
        return oneLevelSubjectList;
    }
}
